package com.personalblog.controller.admin;

import com.personalblog.handler.ApiNotFindUserException;
import com.personalblog.po.User;
import com.personalblog.service.UserService;

import com.personalblog.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author jxau_scf
 * @date 2021/2/22 - 20:57
 */
@Controller
@RequestMapping("/admin")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;


    @PostMapping("/login")
    public String checkLogin(@RequestParam String username, @RequestParam String password, RedirectAttributes attributes){
        try {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, MD5Utils.code(password));
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
            return "admin/index";
        }catch (Exception e){
            logger.info("Login Error:", e);
            Throwable cause = e.getCause();
            if (cause instanceof ApiNotFindUserException){
                if (cause.getMessage() != null){
                    logger.info(e.getMessage());
                }
            }else if (cause instanceof IncorrectCredentialsException){
                logger.info("密码错误");
            }else {
                logger.info("登录失败");
            }
                        //使重定向页面可以传递数据
            attributes.addFlashAttribute("message", "用户名或密码错误");
            return "redirect:/admin";
        }

    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            subject.logout();
        }
        return "redirect:/admin";
    }

    @RequiresPermissions(value = {"CUSTOMER_USER:DELETE","AREA_MANAGER:SELECT"}, logical = Logical.OR)
    @GetMapping("/queryUserInfo")
    @ResponseBody
    public String queryUserInfo(){
        User user = null;
        try {
            user = userService.findUserByUserName("admin");

        }catch (Exception e){
            logger.error("queryUserInfo error:",e);
        }
        return user.toString();
    }







    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

//    @PostMapping("/login")
//    public String login(@RequestParam String username, @RequestParam String password, HttpSession session, RedirectAttributes attributes) {
//        User user = userService.findUserByUsernameAndPassword(username, password);
//        if (user != null) {
//            user.setPassword(null);
//            session.setAttribute("user", user);
//            return "admin/index";
//        } else {
//            //使重定向页面可以传递数据
//            attributes.addFlashAttribute("message", "用户名或密码错误");
//            return "redirect:/admin";
//        }
//    }

//    @GetMapping("/logout")
//    public String logout(HttpSession session){
//        session.removeAttribute("user");
//        return "redirect:/admin";
//    }



//    @RequestMapping("/queryAll")
//    public String findAllUser(Model model){
//        List<User> userList = new ArrayList<>();
//        userList = userService.queryAll();
//
//        model.addAttribute("list",userList);
//
//        return "list";
//    }
}
